package com.atguigu.java;

import org.junit.Test;

import java.io.*;

public class FileReaderWriterTest {



    @Test
    public void test() throws IOException {
        FileReader fr = null;
        try {
            File file =new File("hello.txt");
            fr = new FileReader(file);
            int data;
            while((data=fr.read())!=-1){
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fr!=null){
                    fr.close();

                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }


    }
    @Test
    public void test2() throws IOException {
        FileReader fr = null;
        try {
            File file = new File("hello.txt");
            fr = new FileReader(file);
            char[]cbuf=new char[5];
            int len;
            fr.read(cbuf);
            while((len=fr.read(cbuf))!=-1){
                String str=new String(cbuf,0,len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {


            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    @Test
    public void test3() throws IOException {
        FileWriter fw = null;
        try {
            File file = new File("hello1.txt");
            fw = new FileWriter(file,true);
            fw.write("I love you\n");
            fw.write("i hate you");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
    @Test
    public void test4() throws IOException {
        FileReader fr=null;
        FileWriter fw= null;
        try {
            File f1 = new File("hello1.txt");
            File f2 = new File("hello2.txt");
             fr = new FileReader(f1);
             fw = new FileWriter(f2);
            char[]cbuf=new char[5];
            int len;
            while((len=fr.read(cbuf))!=-1){
                fw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fw!=null)
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (fr!=null)
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
    }


}
